﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServerFrame
{
    public class TransModelCode
    {
        /// <summary>
        /// 传输模型编码
        /// </summary>
        /// <param name="tran">传输模型</param>
        /// <returns>返回字节数组</returns>
        public static byte[] TransModelECode(TransModel tran)
        {
            MemoryStream ms = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(ms);
            bw.Write(tran.type);
            bw.Write(tran.area);
            bw.Write(tran.command);
            if (tran.message != null)
            {
                //序列化message，并写入ms流
                byte[] value = SerializationClass.Serialization(tran.message);
                bw.Write(value);
            }
            byte[] result = new byte[ms.Length];
            Buffer.BlockCopy(ms.GetBuffer(), 0, result, 0, result.Length);
            ms.Close();
            bw.Close();
            return result;
        }
        /// <summary>
        /// 传输模型解码
        /// </summary>
        /// <param name="data">字节数组</param>
        /// <returns>返回传输模型</returns>
        public static TransModel TransModelDeCode(byte[] data)
        {
            TransModel tran = new TransModel();
            MemoryStream ms = new MemoryStream(data);
            BinaryReader br = new BinaryReader(ms);
            tran.type = br.ReadByte();
            tran.area = br.ReadInt32();
            tran.command = br.ReadInt32();
            if (ms.CanRead)
            {
                //反序列化message，并赋值给tran.message
                byte[] value = new byte[ms.Length - ms.Position];
                value = br.ReadBytes(value.Length);
                tran.message = SerializationClass.DeSerialization(value);
            }
            ms.Close();
            br.Close();
            return tran;
        }
    }
}
